<script lang="ts" setup>
import { Form, Select } from 'ant-design-vue'
import type { AfterFetchContext } from '@vueuse/core'
import type { IBefore } from '~/types/apis/before'
import type { IBasic } from '~/types/apis/basic'

defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  differentFields: {
    type: Array,
    default: []
  }
})

const beforeCaseIds = defineModel<string>('beforeCaseIds', { required: true })

const beforeCaseList = ref<IBefore[]>([])
const { isFetching: loadingWithGetBeforeCase, data: beforeCases } =
  useCustomFetch<IBefore[]>(`/engine-service/api/v1/before_case/list`, {
    afterFetch(ctx: AfterFetchContext<IBasic<IBefore[]>>) {
      if (ctx.data && ctx.data.code === 0) {
        beforeCaseList.value = ctx.data.data
        return {
          data: ctx.data.data,
          response: ctx.response,
        }
      }
      return {
        data: [],
        response: ctx.response,
      }
    },
  })

const handleSearch = (value: string) => {
  if (value === '') {
    beforeCaseList.value = beforeCases.value;
  } else {
    beforeCaseList.value = beforeCases.value.filter((item: IBefore) => {
      return item.name.includes(value)
    })
  }

}

const handleChange = (value: string[]) => {
  beforeCaseIds.value = value
  beforeCaseList.value = beforeCases.value;
}

</script>

<template>
  <Form.Item label="前置用例：" :class="{ 'custom-label': differentFields.includes('before_case') }">
    <Select v-model:value="beforeCaseIds" mode="multiple" :loading="loadingWithGetBeforeCase" show-search
      :default-active-first-option="false" :filter-option="false" :not-found-content="null" @search="handleSearch"
      @change="handleChange" placeholder="请选择前置用例">
      <Select.Option v-for="{ id, name, description } in beforeCaseList" :key="id" :value="id">
        <Tooltip :title="description">{{ name }}</Tooltip>
      </Select.Option>
    </Select>
  </Form.Item>
</template>

